var appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    tree:{},
    search:{

      key:'',
      category:'',
    },
    goods:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    this.category_list();
    this.product_list();
  },

  category_list:function( resolve ){

    var url = appInstance.globalData.api_path+'&r=category.tree';

    var t = this;

    appInstance.request( url, {}, 'GET', function( res ){

      if( res.data ){

        t.setData({
          tree:res.data
        });

        if( typeof resolve == 'function'){
          resolve( res.data );
        }

      }

    });

  },

  product_list:function( resolve ){

    var url = appInstance.globalData.api_path+'&r=goods.index';

    var t = this;

    var data = {

      key: this.data.search.key,
      category:this.data.search.category,

    };

    appInstance.request( url, data, 'GET', function( res ){

      if( res.data ){

        t.setData({
          goods:res.data
        });
        if( typeof resolve == 'function'){
          resolve( res.data );
        }
      }

    });

  },

  gotoBuy:function( e ){

    var product = e.currentTarget.dataset.product;
    wx.navigateTo({
      url:'/pages/checkout/checkout?product_id=' + product.id,
    });

  },

  search_by_key:function( e ){

    console.log( e );
    this.data.search.key = e.detail.value;
    this.setData({
      search:this.data.search
    },function(){
      this.product_list();
    });


  },

  search_by_category:function( e ){

    this.data.search.category = e.currentTarget.dataset.category.id;
    this.setData({
      search:this.data.search
    },function(){
      this.product_list();
    });


  },

  search_clear:function(){

    this.setData({
      search:{
        key:'',
        category:''
      }
    },function(){
      this.product_list();
    });


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var p1 = new Promise( this.category_list );
    var p2 = new Promise( this.product_list );
    var p = Promise.all([ p1,p2 ]);
    p.then(function( result ){

      console.log( 'promise' );
      console.log( result );
      wx.stopPullDownRefresh();

    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})